import re
import signal
import time
from socket import *
from datetime import datetime
from multiprocessing import Process

import redis
pool = redis.ConnectionPool(host="localhost",port=6379,db=0)
r = redis.Redis(connection_pool=pool)

danmu_re = re.compile(b'txt@=(.+?)/cid@')
username_re = re.compile(b'nn@=(.+?)/txt@')


client = socket(AF_INET,SOCK_STREAM)
host = gethostbyname('openbarrage.douyutv.com')
client.connect((host,8601))

def save_to_redis(info):
    t = datetime.now().strftime('%F %T')
    #print(t)
    r.hmset(t,info)
    print(t,':',info)

def send_msg(msg):
    msg = msg.encode('utf-8')
    data_length = len(msg) + 8
    code = 689
    msgHead = data_length.to_bytes(4,'little') + data_length.to_bytes(4,'little') + code.to_bytes(4,'little')

    # msgHead = int.to_bytes(data_length, 4, 'little') \
    #           + int.to_bytes(data_length, 4, 'little') + \
    #           int.to_bytes(code, 4, 'little')
    #print('发送请求')
    client.send(msgHead)
    sent = 0
    while sent < len(msg):
        n = client.send(msg[sent:])
        sent += n


def get_dm(roomid):
    #print('登录')
    login = 'type@=loginreq/roomid@={}/\0'.format(roomid)
    # login = 'type@=loginreq/roomid@=%d/\0'%roomid
    send_msg(login)
    #print(login)
    msg_more = 'type@=joingroup/rid@={}/gid@=-9999/\0'.format(roomid)
    send_msg(msg_more)
    while True:
        #print('等待消息')
        data = client.recv(1024)
        danmu_user = re.findall(username_re,data)
        danmu_content = re.findall(danmu_re,data)

        # print('姓名',danmu_user)
        # print('content',danmu_content)

        info = {}
        if data:
            #print("hhah")
            for i in range(0,len(danmu_user)):
                try:
                    info['name'] = danmu_user[0].decode('utf8')
                    info['content'] = danmu_content[0].decode(encoding='utf8')
                    save_to_redis(info)
                except UnicodeDecodeError:
                    pass
        else:
            break




def log_out():
    msg = 'type@=logout/'
    send_msg(msg)
    print('退出服务器')

def keeplive():
    while True:
        #print('发送心跳包')
        keep = 'type@=keeplive/tick@=' + str(time.time()) + '/\0'
        send_msg(keep)
        time.sleep(15)

def signal_handle(signal,frame):
    p1.terminate()
    p2.terminate()
    log_out()
    print('bye')

if __name__ == '__main__':
    roomid = 288016
    signal.signal(signal.SIGINT,signal_handle)
    p1 = Process(target=get_dm,args=(roomid,))
    p2 = Process(target=keeplive)
    p1.start()
    p2.start()
    # p1.join()
    # p2.join()